<?php
/**
 * UserController is for all users.
 * 
 * Bocheng Chen, 18.07.2012
 * 
 * LBB Solutions Oy 版权所有 @ 2012
 */
class UserController extends Controller
{
	public function actionIndex()
	{
		$sql_user_info = 'SELECT u.mobile, u.email, u.picture, u.name, u.first_name, u.last_name, u.gender, u.location, u.lang,
				SUM(t.point) as points, SUM(t.amount) as amount
			FROM tbl_user_account u
			LEFT JOIN tbl_visit_transaction t ON u.id=t.id_user
			WHERE u.id=:id_user ';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_user_info);
		$row = $command->queryRow(true, array(':id_user' => Yii::app()->user->id));
		$connection->active = false;
		
		$this->render('index', array('row'=>$row));
	}
	
	public function actionProfile()
	{
		$sql_user_info = 'SELECT u.mobile, u.email, u.picture, u.name, u.first_name, u.last_name, u.gender, u.location, u.lang,
				SUM(t.point) as points, SUM(t.amount) as amount
			FROM tbl_user_account u
			LEFT JOIN tbl_visit_transaction t ON u.id=t.id_user
			WHERE u.id=:id_user ';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_user_info);
		$row = $command->queryRow(true, array(':id_user' => Yii::app()->user->id));
		$connection->active = false;
		
		$this->render('profile', array('row'=>$row));
	}
	
	public function actionTimeline()
	{
		if (!Yii::app()->request->isAjaxRequest) {
			throw new CHttpException(404, 'The requested page is only for AJAX request.');
		}
		
		//fetch user timeline: only this current month
		$params[':id_user'] = Yii::app()->user->id;
		$params[':this_year'] = (int)date('Y');
		$params[':this_month'] = (int)date('n');
		$sql_user_time = 'SELECT t.id_merchant, t.id_location, t.type, t.message_key, t.message_values, UNIX_TIMESTAMP(t.create_time) AS ts_visit_time
			FROM tbl_user_action_timeline t
			LEFT JOIN tbl_merchant_account m ON m.id=t.id_merchant
			WHERE t.id_user=:id_user AND YEAR(t.create_time)=:this_year AND MONTH(t.create_time)=:this_month
			ORDER BY t.create_time DESC ';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_user_time);
		$rows = $command->queryAll(true, $params);
		$connection->active = false;
		
		$this->renderPartial('_timeline', array('rows'=>$rows));
	}
	
	public function actionSettings()
	{
		if (!Yii::app()->request->isAjaxRequest) {
			throw new CHttpException(404, 'The requested page is only for AJAX request.');
		}
		
		$model = $this->loadModel(Yii::app()->user->id);
		$model->setScenario('settings');
		if (isset($_POST['UserForm'])) {
			$model->attributes = $_POST['UserForm'];
			
			//check the email exists
			if (!empty($model->email) and !empty(Yii::app()->user->email) and $model->email !== Yii::app()->user->email) {
				$sql_email_checking = 'SELECT COUNT(id) FROM tbl_user_account WHERE email=:email AND id<>:id ';
				$connection = Yii::app()->db;
				$command = $connection->createCommand($sql_email_checking);
				$count = $command->queryScalar(array(':email' => $model->email, ':id'=>Yii::app()->user->id));
				$connection->active = false;
				if ($count > 0) {
					$message = '<ul><li style="color:red">'.BUtils::T('duplicate_email_error_msg').'</li></ul>';
					throw new CHttpException(404, $message);
				}
			}
			
			if (!empty($model->mobile)) {
				$model->mobile = CustomerHelper::formatMobile($model->mobile);
			}
			
			if ($model->save()) {
				Yii::app()->user->setState('name', $model->name);
				Yii::app()->user->setState('mobile', $model->mobile);
				Yii::app()->user->setState('email', $model->email);
				Yii::app()->user->setState('lang', $model->lang);
				Yii::app()->user->setState('gender', $model->gender);
				
				echo 'Updated successfully!';
				Yii::app()->end();
			} else {
				//$message = CActiveForm::validate($model);
				$message = '<ul>';
				foreach ($model->errors as $err) {
					$message .= '<li style="color:red">'.$err[0].'</li>';
				}
				$message .= '</ul>';
				throw new CHttpException(404, $message);
			}
		}
		
		$this->renderPartial('_settings', array('model'=>$model));
	}
	
	public function actionPassword()
	{
		if (!Yii::app()->request->isAjaxRequest) {
			throw new CHttpException(404, 'The requested page is only for AJAX request.');
		}
		
		$model = $this->loadModel(Yii::app()->user->id);
		$model->setScenario('password');
		if (isset($_POST['UserForm'])) {
			$model->attributes = $_POST['UserForm'];
			
			//check the password is correct
			$model->password_new = $_POST['UserForm']['password_new'];
			if ($model->validate()) {
				//update password
				$password_in_db = BUtils::Hash32(md5($model->password_new));
				$sql_update = 'UPDATE tbl_user_account SET password=:password WHERE id=:id';
				$connection = Yii::app()->db;
				$command = $connection->createCommand($sql_update);
				$command->execute(array(':id' => Yii::app()->user->id, ':password'=>$password_in_db));
				$connection->active = false;
				echo 'Password is updated successfully!';
				Yii::app()->end();
			} else {
				throw new CHttpException(404, json_encode($model->getErrors()));
			}
		}
		$this->renderPartial('_password', array('model'=>$model));
	}
	
	public function actionNotification()
	{
		if (!Yii::app()->request->isAjaxRequest) {
			throw new CHttpException(404, 'The requested page is only for AJAX request.');
		}
		
		
		
		$this->renderPartial('_notification');
	}
	
	public function actionFacebook()
	{
		if (!Yii::app()->request->isAjaxRequest) {
			throw new CHttpException(404, 'The requested page is only for AJAX request.');
		}
		
		//1. init facebook API SDK
		require_once(Yii::app()->basePath . '/extensions/fbapi/facebook.php');
		$facebook = new Facebook(array(
			'appId'  => Yii::app()->params['facebook']['appId'],
			'secret' => Yii::app()->params['facebook']['secret'],
			'cookie' => true, // enable optional cookie support
		));
		//2. get user profile info
		$userFbId = $facebook->getUser();
		$userFbProfile = null;
		if ($userFbId) {
			try {
				$userFbProfile = $facebook->api('/me');
			} catch (FacebookApiException $e) {
				Yii::log("ERROR : /user/facebook : Get exception of facebook.\n" . $e->getTraceAsString(), CLogger::LEVEL_ERROR);
				BUtils::sendJson(500, $e->getMessage());
			}
		} else {
			Yii::log("ERROR : /user/facebook : Cannot get facebook user id.", CLogger::LEVEL_ERROR);
			BUtils::sendJson(500, Yii::t('Facebook login failed!'));
		}
		if ($userFbProfile) {
			//set login with facebook profile
			$params = array(
				':id' => Yii::app()->user->id,
				':site_user_id' => $userFbProfile['id'],
				':username' => $userFbProfile['username'],
			);
			$sql_update = 'UPDATE tbl_user_account SET site_id=1, site_user_id=:site_user_id, username=:username';
			if (empty(Yii::app()->user->email)) {
				$sql_update .= ', email=:email';
				$params[':email'] = $userFbProfile['email'];
			}
			if (empty(Yii::app()->user->location)) {
				$sql_update .= ', location=:location';
				$params[':location'] = isset($userFbProfile['location']['name']) ? $userFbProfile['location']['name']: '';
			}
			if (empty(Yii::app()->user->picture)) {
				$sql_update .= ', picture=:picture';
				$params[':picture'] = "http://graph.facebook.com/{$userFbProfile['id']}/picture";
			}
			if (empty(Yii::app()->user->gender)) {
				$sql_update .= ', gender=:gender';
				$params[':gender'] = strtolower($userFbProfile['gender']);
			}
			$sql_update .= ', last_login_time=NOW() WHERE id=:id ';
			$connection = Yii::app()->db;
			$command = $connection->createCommand($sql_update);
			$command->execute($params);
			$connection->active = false;
			Yii::app()->user->setState('facebook', 1);
			
			//print_r(array($sql_update, $params, $userFbProfile));
			BUtils::sendJson(200, array(
				'name' => $userFbProfile['name'],
				'email' => $userFbProfile['email'],
				'lang' => substr($userFbProfile['locale'], 0, 2),
				'picture' => $params[':picture'],
				'gender' => $params[':gender'],
			));
		} else {
			Yii::log("ERROR : /user/facebook : Cannot get facebook user information : {$userFbId}", CLogger::LEVEL_ERROR);
			BUtils::sendJson(500, Yii::t('Facebook login failed!'));
		}
	}
	
	/**
	 * e=?
	 * type=?
	 */
	public function actionUnsubscribe()
	{
		$e = Yii::app()->request->getQuery('e');
		$type = Yii::app()->request->getQuery('type');
		if (!empty($e) and !empty($type)) {
			$email = BUtils::Decrypt($e);
			
			$connection = Yii::app()->db;
			$sql_user_subscribe = 'UPDATE tbl_user_subscribe SET unsubscribed_time=NOW(), unsubscribed_reason=:reason
				WHERE id_user IN (SELECT id FROM tbl_user_account WHERE email=:email) AND type=:type ';
			$command = $connection->createCommand($sql_user_subscribe);
			$command->execute(array(
				':reason' => 'unsubscribed from auto-newsletter',
				':email' => $email,
				':type' => $type,
			));
			$connection->active = false;
		}
		
		$this->render('unsubscribe', array('rows' => array(
			'email' => $email,
		)));
	}
	
	/**
	 * AJAX update user inforamtion
	 */
	public function actionUpdate() {
		$name = trim(Yii::app()->request->getPost('user_name'));
		if (empty($name)) {
			BUtils::sendJSON(500, Yii::t('app', 'Please enter your name!'));
		}
		
		$connection = Yii::app()->db;
		$sql_user_name = 'UPDATE tbl_user_account SET name=:name WHERE id=:id ';
		$command = $connection->createCommand($sql_user_name);
		$command->execute(array(
			':name' => $name,
			':id' => Yii::app()->user->id,
		));
		$connection->active = false;
		
		//update the name
		Yii::app()->user->name = $name;
		Yii::app()->user->setState('name', $name);
		BUtils::sendJSON(200, Yii::t('app', 'OK'));
	}

	/**
	 * AJAX activate user points
	 * 
	 * 用户输入邮箱/电话，系统检查这个邮箱或电话的stutus=99，如果是，则系统复制当前用户信息到这个邮箱或电话的ID上面。然后刷新系统。
	 */
	public function actionActivate() {
		$user_input = trim(Yii::app()->request->getParam('user_input'));
		if (empty($user_input)) {
			BUtils::sendJSON(500, Yii::t('app', 'Please enter phone number or email!'));
		}
		
		$sql_check = '';
		$params = array();
		$type = CustomerHelper::getType($user_input);
		switch ($type) {
			case 1:
				$sql_check = 'SELECT id, status FROM tbl_user_account WHERE email=:email';
				$params[':email'] = $user_input;
				break;
			case 2:
				$user_input = CustomerHelper::formatMobile($user_input);
				$sql_check = 'SELECT id, status FROM tbl_user_account WHERE mobile=:mobile';
				$params[':mobile'] = $user_input;
				break;
			default:
				BUtils::sendJSON(500, Yii::t('app', 'The phone number/email is invalid!'));
				break;
		}
		
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_check);
		$row = $command->queryRow(true, $params);
		$connection->active = false;
		if (empty($row['id'])) {
			//not in our user table
			if (1 == $type) BUtils::sendJSON(500, Yii::t('app', 'The email has not been used to earn points!'));
			else BUtils::sendJSON(500, Yii::t('app', 'The phone number has not been used to earn points!'));
		} elseif (99 != $row['status']) {
			//this email/mobile has status=0 already
			if (1 == $type) BUtils::sendJSON(500, Yii::t('app', 'The email has been registered!'));
			else BUtils::sendJSON(500, Yii::t('app', 'The phone number has not been registered!'));
		}
		
		//activate user account
		if (Yii::app()->user->id == $row['id']) {
			//this user ID is same
			$sql_update = 'UPDATE tbl_user_account SET status=1 WHERE id=:id';
			$connection = Yii::app()->db;
			$command = $connection->createCommand($sql_update);
			$command->execute(array(':id'=>Yii::app()->user->id));
			$connection->active = false;
			Yii::app()->user->setState('status', 1);
		} else {
			//this user ID is different
			$currentUser = $this->loadModel((int)Yii::app()->user->id);
			$activeUser = $this->loadModel((int)$row['id']);
			
			$activeUser->password = $currentUser->password;
			$activeUser->username = $currentUser->username;
			$activeUser->picture = $currentUser->picture;
			$activeUser->site_id = $currentUser->site_id;
			$activeUser->site_user_id = $currentUser->site_user_id;
			$activeUser->site_token = $currentUser->site_token;
			$activeUser->name = $currentUser->name;
			$activeUser->first_name = $currentUser->first_name;
			$activeUser->last_name = $currentUser->last_name;
			$activeUser->nick_name = $currentUser->nick_name;
			$activeUser->gender = $currentUser->gender;
			$activeUser->location = $currentUser->location;
			$activeUser->lang = $currentUser->lang;
			$activeUser->time_zone = $currentUser->time_zone;
			if (1 == $type) {
				$activeUser->mobile = $currentUser->mobile;
			} else {
				$activeUser->email = $currentUser->email;
			}
			$activeUser->status = 1;
			$activeUser->save();
			
			//clean the old user entity.
			$currentUser->delete();
			
			Yii::app()->user->id = $activeUser->id;
			Yii::app()->user->setState('status', 1);
		}
		
		BUtils::sendJSON(200, Yii::t('app', 'OK'));
	}
	
	/**
	 * AJAX update the user points.
	 */
	public function actionPoints() {
		if (!Yii::app()->request->isAjaxRequest) {
			throw new CHttpException(404, 'The requested page is only for AJAX request.');
		}
		
		//get mid=?
		$params = array(':id_user'=>Yii::app()->user->id);
		$sql_where = ' WHERE id_user=:id_user ';
		
		$id_merchant = Yii::app()->request->getParam('mid');
		if (!empty($id_merchant)) {
			$sql_where .= ' AND id_merchant=:id_merchant ';
			$params[':id_merchant'] = (int)$id_merchant;
		}
		
		//get sum of points from tbl_visit_customer_notes
		$sql_sum_points = 'SELECT amount, point AS points, spend_points, visit_times, UNIX_TIMESTAMP(update_time) AS ts_update_time '
			. ' FROM tbl_visit_customer_notes '
			. $sql_where;
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_sum_points);
		$rows = $command->queryAll(true, $params);
		$connection->active = false;
		
		$stores = count($rows);
		$current_points = 0;
		$spend_points = 0;
		$visits = 0;
		foreach ($rows as $r) {
			$current_points += $r['points'];
			$spend_points += $r['spend_points'];
			$visits += $r['visit_times'];
		}
		
		BUtils::sendJSON(200, array(
			'stores' => $stores,
			'visits' => $visits,
			'current_pts' => $current_points,
			'spend_pts' => $spend_points
		));
	}

	/**
	 * AJAX fetch all merchants where user has earned points.
	 */
	public function actionMerchants() {
		if (!Yii::app()->request->isAjaxRequest) {
			throw new CHttpException(404, 'The requested page is only for AJAX request.');
		}
		
		if (Yii::app()->user->isGuest) {
			throw new CHttpException(404, 'Sorry! You have not signed in Yamii.');
		}
		
		//get mid=?
		$params = array(':id_user'=>Yii::app()->user->id);
		$sql_where = ' WHERE n.id_user=:id_user LIMIT 21 ';
		
		//get sum of points from tbl_visit_customer_notes
		$sql_merchants = 'SELECT n.id_merchant, n.amount, n.point AS points, n.spend_points, n.visit_times, UNIX_TIMESTAMP(n.update_time) AS ts_update_time,'
			. ' m.seo_id, m.name, m.address, m.biz_area, m.postcode, m.phone, m.city, m.country_code, m.category_key, m.url_logo, m.url_offer_img '
			. ' FROM tbl_visit_customer_notes n'
			. ' INNER JOIN tbl_merchant_account m ON m.id=n.id_merchant '
			. $sql_where;
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_merchants);
		$rows = $command->queryAll(true, $params);
		$connection->active = false;
		$this->renderPartial('_merchants', array('rows'=>$rows));
	}
	
	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
			'accessControl', // perform access control for CRUD operations
			array(
                'COutputCache + points, timeline', // Cache for actionNearby
                'duration' => 3600, // 1 hour
				'varyBySession' => true,
            ),
		);
	}
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
			array('allow', // allow all user
				'actions'=>array('view', 'unsubscribe'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user
				//'actions'=>array('index', 'account', 'special'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				//'actions'=>array('index', 'account', 'special'),
				'users'=>array('*'),
			),
		);
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	protected function loadModel($id)
	{
		$model = UserForm::model()->findByPk($id);
		if ($model===null)
			throw new CHttpException(404, 'The requested page does not exist.');
		return $model;
	}
}